#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <string.h>
#include <arpa/inet.h>
#include <ctype.h>
#include <sys/select.h>
#include <net/if.h>

int main(int argc, const char *argv[])
{
    // 创建套接字
    int fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (fd == -1)
    {
        printf("创建套接字失败\n");
        exit(1);
    }
    struct sockaddr_in serv;
    memset(&serv, 0, sizeof(serv));
    inet_pton(AF_INET, "0.0.0.0", &serv.sin_addr.s_addr);
    //   serv.sin_addr.s_addr = htonl(INADDR_ANY);
    serv.sin_family = AF_INET;
    serv.sin_port = htons(6767); // 指定端口
    socklen_t len = sizeof(serv);
    bind(fd, (const struct sockaddr *)&serv, len);

    // 加入到组播地址
    struct ip_mreqn fl;
    inet_pton(AF_INET, "239.0.0.10", &fl.imr_multiaddr.s_addr);
    inet_pton(AF_INET, "0.0.0.0", &fl.imr_address.s_addr);
    fl.imr_ifindex = if_nametoindex("wlp3s0");
    setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &fl, sizeof(fl));
    while (1)
    {
        char buf[1024] = {0};
        // 等待服务器发送数据过来
        recvfrom(fd, buf, sizeof(buf), 0, NULL, NULL);
        printf("recv buf:%s\n", buf);
    }
    close(fd);
    return 0;
}
